package com.eckey.lab.dubbo.interfaces;

import com.alibaba.fastjson.JSON;
import com.eckey.lab.common.Result;
import com.eckey.lab.dubbo.bean.User;
import com.eckey.lab.dubbo.dao.UserDao;
import com.eckey.lab.interfaces.UserProviderAPI;
import com.eckey.lab.interfaces.bean.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;


import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author: ChengLiang
 * @CreateTime: 2023-11-13  10:11
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
@Service(version = "1.0.0", timeout = 6000)
@Component
public class UserProviderServiceImpl implements UserProviderAPI {

    @Resource
    private UserDao userDao;

    @Override
    public Result insert(UserDTO user) {
        log.info("添加user入库数据：{}", JSON.toJSONString(user));
        if (user == null) {
            log.error("user不为空");
            return Result.buildDataError("user不为空");
        }
        try {
            user.setCreateTime(new Date());
            user.setModifyTime(new Date());
            User userInsert = new User();
            userInsert.setUserName(user.getUserName());
            userInsert.setNickName(user.getNickName());
            userInsert.setGender(user.getGender());
            userInsert.setAge(user.getAge());
            userInsert.setCreateTime(user.getCreateTime());
            userInsert.setModifyTime(user.getModifyTime());
            userDao.insert(userInsert);
            log.info("数据添加成功：{}", JSON.toJSONString(user));
        } catch (Exception e) {
            log.error("添加数据异常：{}", e);
            return Result.buildDataError("添加数据异常");
        }
        return Result.buildResultSuccess();
    }

    @Override
    public Result<UserDTO> queryById(Integer id) {
        if (id == null) {
            log.error("id不能为空");
            return Result.buildDataError("id不能为空");
        }
        final User user = userDao.selectByPrimaryKey(id);
        final UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user, userDTO);
        log.info("查询结果为：{}", JSON.toJSONString(userDTO));
        return Result.buildDataSuccess(userDTO);
    }
}
